package com.noahsloan.nutils.streams.clocked;

import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * InputStream that can report its data rate.
 * 
 * @author noah
 * 
 */
public class ClockedInputStream extends FilterInputStream {

    private final RateCalculator clock;

    public ClockedInputStream(InputStream in) {
        this(in, 1000);
    }

    public ClockedInputStream(InputStream in, long interval) {
        this(in, new FixedWindowCalc(interval,
                new ClockTimer.DefaultTimeSource()));
    }

    /**
     * 
     * @param in
     *            the stream to measure
     * @param interval
     *            the interval to measure over. e.g. 3000ms.
     */
    public ClockedInputStream(InputStream in, RateCalculator calc) {
        super(in);
        clock = calc;
    }

    @Override
    public int read() throws IOException {
        clock.storeMeasurement(1);
        return super.read();
    }

    @Override
    public int read(byte[] b) throws IOException {
        return read(b, 0, b.length);
    }

    @Override
    public int read(byte[] b, int off, int len) throws IOException {
        int i = super.read(b, off, len);
        clock.storeMeasurement(i);
        return i;
    }

    @Override
    public void close() throws IOException {
        super.close();
    }

    public double getRate() {
        return clock.getRate();
    }
}
